package com.rtsapp.server.gamelog.analyze.stat;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * Created by admin on 16-7-28.
 */
public class DateUtils {

    public static final int DAY_IN_MILLIS = 24 * 60 * 60 * 1000;


    /**
     * 计算星期几
     *
     * @param dt
     * @return
     */
    public static String getWeekOfDate( Date dt ) {
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance( );
        cal.setTime( dt );
        int w = cal.get( Calendar.DAY_OF_WEEK ) - 1;
        if ( w < 0 ) {
            w = 0;
        }
        return weekDays[ w ];
    }


    public static Date increaseDate( Date date, int days ) {
        Calendar c = new GregorianCalendar( );
        c.setTime( date );
        c.add( Calendar.DAY_OF_MONTH, days );
        return c.getTime( );
    }

    public static boolean isDateBefore( Date date, Date endDay ) {
        return date.before(endDay);
    }

    public static String convertDateToString( Date date ){
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 判断一个 毫秒时间戳 是不是今天
     * 如果为null则视为不是今天
     */
    public static boolean isToday( Long time ) {
        if ( time == null ) {
            return false;
        }
        return msecToDay( time ) == msecToDay( System.currentTimeMillis( ) );
    }

    /**
     * 判断两个毫秒时间戳是不是在同一天内
     *
     * @param time1
     * @param time2
     * @return
     */
    public static boolean isSameDay( long time1, long time2 ) {
        return msecToDay( time1 ) == msecToDay( time2 );
    }

    /**
     * 将一个毫秒时间戳, 转换为一个天数时间戳
     */
    private static long msecToDay( long time ) {
        // 时间 - 时区时间差!
        return ( time + TimeZone.getDefault( ).getRawOffset( ) ) / DAY_IN_MILLIS;
    }


    /**
     * 获取一个时间点所属的当天的开始时间
     *
     * @param time
     * @return
     */
    public static long getDayStartTime_MS( long time ) {
        Calendar cal = Calendar.getInstance( );
        cal.setTimeInMillis( time );

        cal.set( Calendar.HOUR_OF_DAY, 0 );
        cal.set( Calendar.MINUTE, 0 );
        cal.set( Calendar.SECOND, 0 );
        cal.set( Calendar.MILLISECOND, 0 );

        return cal.getTimeInMillis( );
    }


}
